package com.comment.util.pay;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 质押
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Pledge<T> {
    private static final Logger logger = LoggerFactory.getLogger(Pledge.class);
    private static final ConcurrentHashMap<String, Pledge<?>> PLEDGE_CACHE = new ConcurrentHashMap<>();

    /**
     * 质押密钥
     */
    private String key;

    /**
     * 质押人
     */
    private Long playerId;

    /**
     * 质押物品
     */
    private T pledgeProp;

    /**
     * 质押物品
     *
     * @param pledgeKey  质押密钥
     * @param playerId   玩家id
     * @param pledgeProp 质押物品
     * @return 返回质押密钥
     */
    public static <T> String init(String pledgeKey, Long playerId, T pledgeProp) {
        if (pledgeKey == null || playerId == null || pledgeProp == null) {
            throw new IllegalArgumentException("pledgeKey、playerId和pledgeProp不能为空");
        }
        Pledge<T> pledge = new Pledge<>(pledgeKey, playerId, pledgeProp);
        PLEDGE_CACHE.put(pledgeKey, pledge);
        logger.info("Pledge initialized with key: {}", pledgeKey);
        return pledge.getKey();
    }

    /**
     * 解除质押
     *
     * @param pledgeKey 质押密钥
     */
    public static void unPledge(String pledgeKey) {
        if (pledgeKey == null) {
            throw new IllegalArgumentException("pledgeKey不能为空");
        }
        PLEDGE_CACHE.remove(pledgeKey);
        logger.info("解除质押: {}", pledgeKey);
    }

    /**
     * 赎回
     *
     * @param pledgeKey 质押密钥
     * @return 返回被质押的物品
     */
    public static Optional<Pledge<?>> redeem(String pledgeKey) {
        if (pledgeKey == null) {
            throw new IllegalArgumentException("pledgeKey cannot be null");
        }
        Pledge<?> pledge = PLEDGE_CACHE.remove(pledgeKey);
        if (pledge != null) {
            logger.info("Pledge redeemed with key: {}", pledgeKey);
        } else {
            logger.warn("Attempt to redeem non-existent pledge with key: {}", pledgeKey);
        }
        return Optional.ofNullable(pledge);
    }

    public static String obtainKey(String info) {
        return info + "-" + UUID.randomUUID();
    }
}
